<template>
  <div>
    <div class="app-container">
      <div class="search-container">
        <el-form :inline="true" :model="startQuerys" class="demo-form-inline">
          <el-form-item label="耳号">
            <el-input v-model="startQuerys.earTag" placeholder="请输入耳号"></el-input>
          </el-form-item>
          <!--转种日期:区间查询-->
          <el-form-item label="转种日期">
            <el-col :span="11">
              <el-date-picker v-model="startQuerys.sdate" type="date" placeholder="开始日期" style="width: 100%" />
            </el-col>
            <el-col :span="2" class="text-center">
              <span class="text-gray-500">-</span>
            </el-col>
            <el-col :span="11">
              <el-date-picker v-model="startQuerys.edate" placeholder="结束日期" style="width: 100%" />
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="GetRamList">查询</el-button>
            <el-button type="danger" :icon="Delete" @click="DelRange">批量删除</el-button>

            <el-button type="primary" @click="AddRam">添加</el-button>
            <!--导出-->
            <el-button type="warning" @click="exportData">导出</el-button>&emsp;
            <!--导入-->


            <el-upload ref="uploadRef" class="upload-demo"
              action="https://localhost:56100/api/Start/ImportStartData/import" :auto-upload="true"
              show-file-list="true" :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError"
              style="margin-top: 10px;">
              <template #trigger>
                <el-button type="success">导入</el-button>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>

      </div>
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />

        <el-table-column prop="startId" label="序号" />
        <el-table-column prop="documentNumber" label="单据号" />
        <el-table-column prop="openingDate" label="期初日期">
          <template v-slot="scope">
            {{ scope.row.openingDate.substring(0, 10) }}
          </template>
        </el-table-column>
        <el-table-column prop="earTag" label="耳号" />
        <el-table-column prop="ridgepoleName" label="栋舍名称" />
        <el-table-column prop="columnName" label="栏位" />
        <el-table-column prop="" label="转种日期">
          <template v-slot="scope">
            {{ scope.row.replantingDate.substring(0, 10) }}
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="重量（公斤）" />
        <el-table-column prop="createName" label="创建人" />
        <el-table-column prop="" label="创建时间"> <template v-slot="scope">
            {{ scope.row.createDate.substring(0, 10) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateName" label="修改人" />
        <el-table-column prop="" label="修改时间">
          <template v-slot="scope">
            {{ scope.row.updateDate.substring(0, 10) }}
          </template>
        </el-table-column>

        <el-table-column prop="breedingBatchName" label="操作">
          <template v-slot="scope">
            <el-link :icon="Edit" type="primary" @click="edit(scope.row)">编辑</el-link>&emsp;
            <el-link :icon="Delete" type="danger" @click="del(scope.row.startId)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-model="dialogVisible" title="Tips" width="500">
        <span>
          <el-form :model="form" label-width="120px">
            <el-form-item label="羊只编号">
              <el-input v-model="form.startId"></el-input>
            </el-form-item>
            <el-form-item label="耳号">
              <el-select v-model="form.earTag" placeholder="请选择耳号">
                <el-option v-for="item in mathererars" :key="item.earTag" :label="item.earTag" :value="item.earTag" />
              </el-select>
            </el-form-item>
            <el-form-item label="栋舍">
              <el-select v-model="form.ridgepoleId" placeholder="请选择栋舍ID" @change="getcolumnIdList(form.ridgepoleId)">
                <el-option :label="item.ridgepoleName" :value="item.ridgepoleId" v-for="item in buildingIdList" />
              </el-select>
            </el-form-item>
            <el-form-item label="栏位">
              <el-select v-model="form.columnManagementId" placeholder="请选择栏位ID">
                <el-option :label="item.columnName" :value="item.columnManagementId" v-for="item in columnIdList" />
              </el-select>
            </el-form-item>
            <el-form-item label="转种日期">
              <el-date-picker v-model="form.replantingDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" type="date"
                placeholder="选择日期" />
            </el-form-item>
            <el-form-item label="只数">
              <el-input v-model="form.onlyNumber" />
            </el-form-item>
            <el-form-item label="重量">
              <el-input v-model="form.weight" />
            </el-form-item>
            <el-form-item>
              <el-button @click="UptRam" type="primary">确定</el-button>
              <el-button @click="dialogVisible = false" type="danger">取消</el-button>
            </el-form-item>
          </el-form>
        </span>
      </el-dialog>
      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="startQuerys.pageIndex" v-model:page-size="startQuerys.pageSize"
          :page-sizes="[2, 3, 4, 5]" :background="true" layout="total, sizes, prev, pager, next, jumper" prev-text="上一页"
          next-text="下一页" :total="page.totalCount" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />

      </div>
    </div>
  </div>

</template>
<script setup lang="ts">

import start from '@/api/BreedingManagement/index'
import { startAdd } from '@/api/BreedingManagement/model'
import { startQuery } from '@/api/BreedingManagement/model'

//耳号
import sheepfile from '@/api/ProductionManagement/index'

//栋舍栏位
import purcure from '@/api/PurchaseMent/index'
import { purcoreQuery, buildingIdQuery } from '@/api/PurchaseMent/model'


import {

  Delete,
  Edit,
  Search,
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter();
//对话框
const dialogVisible = ref(false)


//参数
const startQuerys = reactive<startQuery>({
  type: 2,
  earTag: "",
  pageIndex: 1,
  pageSize: 15,
  sdate: "",
  edate: "",
})
//分页
const page = reactive({
  pageCount: 0,
  totalCount: 0
})

const handleSizeChange = (val: number) => {
  startQuerys.pageSize = val
  GetRamList()
}
const handleCurrentChange = (val: number) => {
  startQuerys.pageIndex = val;
  GetRamList()
}

//显示
const tableData: any = ref([])
const GetRamList = () => {
  start.getList(startQuerys).then((res: any) => {
    console.log('完整响应数据:', res);
    tableData.value = res.data.data
    page.pageCount = res.data.pageCount
    page.totalCount = res.data.totalCount
  })
}
onMounted(() => {
  GetRamList()
})

const pagelist = reactive({
  total: 0,
  totalPage: 0
})

//母亲耳号
const mathererars = ref([])
const getSheepmaears = () => {
  const form = reactive({
    presentState: 0,
    sheepType: 2
  })
  sheepfile.updatesheepfilestatus(form.presentState, form.sheepType).then(res => {
    mathererars.value = res.data
  })
}



//获取栋舍
const forms = reactive<buildingIdQuery>({
  "pageIndex": 1,
  "pageSize": 100,
  "ridgepoleTypeId": 0,
  "ridgepoleName": "",
  "responsiblePerson": ""
})
const buildingIdList: any = ref([])
const getBuildingIdList = () => {
  purcure.getrid(forms).then((res: any) => {
    buildingIdList.value = res.data.data
  })
}
//获取栏位
const columnIdList: any = ref([])
const getcolumnIdList = (id: any) => {
  console.log(id)
  purcure.getcolumn(id).then((res: any) => {
    columnIdList.value = res.data
    console.log(columnIdList.value)
  })
  columnIdList.value = []
}

onMounted(() => {
  getSheepmaears();
  getBuildingIdList();

});



//导出

const exportData = () => {

  window.location.href = "https://localhost:56100/api/Start/ExportStart?type=2" + "&earTag=" + startQuerys.earTag + "&pageIndex=" + startQuerys.pageIndex
    + "&pageSize=" + startQuerys.pageSize + "&sdate=" + startQuerys.sdate
    + "&edate=" + startQuerys.edate
    + "&pageSize=1000&pageIndex=1"
}
//导入
const uploadRef = ref<UploadInstance | null>(null);

const beforeUpload = (file: File) => {
  const isExcel =
    file.type === 'application/vnd.ms-excel' ||
    file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!');
  }
  return isExcel;
};

const handleSuccess = (response: any, file: File, fileList: File[]) => {
  console.log('上传成功', response, file, fileList);
  ElMessage.success('文件上传成功!');

  // 清除上传的文件
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
  // 刷新表格数据（这里用 console.log 模拟刷新表格数据）
  console.log('刷新表格数据...');
};

const handleError = (err: any, file: File, fileList: File[]) => {
  console.log('上传失败', err, file, fileList);
  ElMessage.error('文件上传失败!');
};

//删除
const del = (id: number) => {
  ElMessageBox.confirm(
    '确认删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    start.deleteStart(id).then((res: any) => {
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      GetRamList()
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除',
    })
  })

}


const idlist: any = ref([])
//已选择几项  
const checked = ref(0)
const handleSelectionChange = (val: any) => {
  checked.value = val.length; // 更新选中项的数量

  // 如果需要获取选中项的 ID 列表，可以进一步处理
  idlist.value = val.map((item: any) => item.startId); // 假设每个选中项有一个唯一的 id 属性

}
//批量删除
const DelRange = () => {
  console.log(idlist.value)

  if (checked.value == 0) {
    ElMessage({
      message: '请选择要删除的项',
      type: 'warning',
    })
    return;
  }
  ElMessageBox.confirm(
    '确认批量删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    start.deleteBatchStart(idlist.value).then((res: any) => {
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      GetRamList()
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除',
    })
  })


}


//添加
const AddRam = () => {
  router.push({
    name: 'EarlyBreedingHen',

  })
}


//添加修改字段

const form = reactive<startAdd>({
  type: 1,
  earTag: '',
  ridgepoleId: 0,
  columnManagementId: 0,
  weight: 0,
  onlyNumber: 0,
  remark: '',
  documentNumber: '',
  stage: 0,
  isdel: false,
  replantingDate: '2024-07-27',
  openingDate: '',
  createDate: '',

})
//修改
const edit = (data: any) => {
  dialogVisible.value = true;
  form.startId = data.startId
  form.type = data.type

  form.earTag = data.earTag
  getBuildingIdList()
  form.ridgepoleId = data.ridgepoleId
  getcolumnIdList(form.ridgepoleId)
  form.columnManagementId = data.columnManagementId
  form.weight = data.weight
  form.onlyNumber = data.onlyNumber
  form.remark = data.remark
  form.documentNumber = data.documentNumber
  form.replantingDate = data.replantingDate
  form.openingDate = data.openingDate
  form.createDate = data.createDate
  form.stage = data.stage
  form.isdel = data.isdel

}


const UptRam = () => {
  ElMessageBox.confirm(
    '确定要修改吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    //修改
    start.updateStart(form).then(res => {
      if (res.data > 0) {
        ElMessage({
          message: '修改成功',
          type: 'success',
        })
        dialogVisible.value = false;
        GetRamList()
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消修改',
    })
  })
}



</script>
